class RentalsController < ApplicationController
  
  def list_rentals_by_book_or_user
    @rental = Rental.new(params[:rental])    
    session[:rentals] = Rental.find(:all,
                                    :conditions => ["book_title LIKE ? AND user_name LIKE ?",
                                      "%#{@rental.book_title}%", "%#{@rental.user_name}%"])
  end

  def list_rentals_by_date
    @rental = Rental.new(params[:rental])
    session[:rentals] = Rental.find(:all,
                                    :conditions => ["pick_up > ? AND pick_up < ?",
                                      "#{@rental.pick_up}", "#{@rental.return.tomorrow}"])
  end
  
  # GET /rentals
  # GET /rentals.xml
  def index
    @rentals = Rental.find(:all, :order => :pick_up)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @rentals }
    end
  end

  # GET /rentals/1
  # GET /rentals/1.xml
  def show
    @rental = Rental.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @rental }
    end
  end

  # GET /rentals/new
  # GET /rentals/new.xml
  def new
    @rental = Rental.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @rental }
    end
  end

  # GET /rentals/1/edit
  def edit
    @rental = Rental.find(params[:id])
  end

  # POST /rentals
  # POST /rentals.xml
  def create
    @rental = Rental.new(params[:rental])

    respond_to do |format|
      if @rental.save
        flash[:notice] = 'Empréstimo realizado com sucesso.'
        format.html { redirect_to(@rental) }
        format.xml  { render :xml => @rental, :status => :created, :location => @rental }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @rental.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /rentals/1
  # PUT /rentals/1.xml
  def update
    @rental = Rental.find(params[:id])

    respond_to do |format|
      if @rental.update_attributes(params[:rental])
        @book = Book.find(@rental.book_id)
        @book.quantity += 1
        @book.save
        flash[:notice] = 'Devolução realizada com sucesso.'
        format.html { redirect_to(@rental) }
        format.xml  { head :ok }        
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @rental.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /rentals/1
  # DELETE /rentals/1.xml
  def destroy
    @rental = Rental.find(params[:id])
    @book = Book.find(@rental.book_id)
    @book.quantity += 1
    @book.save
    @rental.destroy

    respond_to do |format|
      format.html { redirect_to(rentals_url) }
      format.xml  { head :ok }
    end
  end
end
